package com.dao;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    static {
        Properties properties = new Properties();
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");

        try{
            properties.load(is);
        }catch(IOException e){
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    //获取连接
    public static Connection getConnection(){
        Connection con = null;
        try{
            Class.forName(driver);
            con = DriverManager.getConnection(url,username,password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return con;
    }

    //查询
    public static ResultSet execute(Connection con,String sql,Object[] params,ResultSet result,PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = con.prepareStatement(sql);
        for(int i=0;i<params.length;i++){
            preparedStatement.setObject(i+1,params[i]);
        }
        result = preparedStatement.executeQuery();
        return result;
    }

    //增删
    public static int execute(Connection con,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = con.prepareStatement(sql);
        for(int i=0;i<params.length;i++){
            preparedStatement.setObject(i+1,params[i]);
        }
        int updateRows = preparedStatement.executeUpdate();
        return updateRows;
    }

    //释放资源
    public static boolean closeResource(Connection con,ResultSet result,PreparedStatement preparedStatement){
        boolean flag = true;
        if(result != null){
            try{
                result.close();
                result = null;
            }catch (SQLException e){
                e.printStackTrace();
                flag = false;
            }
        }
        if(preparedStatement != null){
            try{
                result.close();
                result = null;
            }catch (SQLException e){
                e.printStackTrace();
                flag = false;
            }
        }
        if(con != null){
            try{
                con.close();
                con = null;
            }catch (SQLException e){
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}
